import java.util.List;

import cn.accp.bookshop.Book;



public class BookJSONHelper {
	/**
	 * 将传入的book对象，拼接成如下字符串格式
	 *  {"id":1,"title":"c++","price":12}
	 * @param book
	 * @return
	 */
	public static String toJson(Book book){
		StringBuffer jsonBuffer=new StringBuffer();
		jsonBuffer.append(String.format("{\"id\":%d,\"title\":\"%s\",\"price\":%.2f}",
				book.getId(),
				book.getTitle(),
				book.getPrice()
					)
				);
		return jsonBuffer.toString();
	}
	/**
	 * 将一个json格式的字符串，转成图书对象
	 * {"id":1,"title":"c++","price":12}
	 * @param json
	 * @return
	 */
	public static Book toBook(String json){
		String string=	json.replaceAll("\"", "");
		String[]parts=string.split(",");		
		int id=Integer.parseInt(parts[0].split(":")[1]);
		String title=parts[1].split(":")[1];
		//下面这段是获得price:22.00 的，注意，已经把最后一个} 给去掉了
		String priceString=parts[2].split(":")[1].substring(0, parts[2].split(":")[1].length()-1);
		double price=Double.parseDouble( priceString);
		Book book=new Book(id, title, price);
		return book;
	}
	
	
	/**
	 * 将图书集合转换成json格式字符串
	 * [
	 *  {"id":1,"title":"c++","price":12}，
	 *  {"id":1,"title":"c++","price":12}
	 * ]
	 * @param books
	 * @return
	 */
	public static String toJson(List<Book> books){
		StringBuffer jsonBuffer=new StringBuffer("[");
		for (Book book : books) {
			jsonBuffer.append(toJson(book)+",");
		}
		
		//删除最后一个逗号
		jsonBuffer=jsonBuffer.deleteCharAt(jsonBuffer.length()-1);
		jsonBuffer.append("]");
		return jsonBuffer.toString();
	}
	
}






